<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {
	public function index()
	{
		$this->load->helper(array('form'));	
		$this->load->view('admin_login_view');
	}
	public function verify_login(){
		//This method will have the credentials validation
		$this->load->library('form_validation');
		
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
		
		if($this->form_validation->run() == FALSE)
		{
			//Field validation failed.  User redirected to login page
			$this->load->view('admin_login_view');
		}
		else
		{
			//Go to private area
			redirect('admin', 'refresh');
		}
	}
	public function check_database($password)
	{
		//Field validation succeeded.  Validate against database
		$username = $this->input->post('username');
		
		$this->load->model('authentication_model');
		//query the database
		$result = $this->authentication_model->validate_administer_user($username, $password);
	
		if($result)
		{
			$sess_array = array('id' => $result->getId(), 'username' => $result->getUsername(), 'user_level' => $result->getUserLevel());
			$this->session->set_userdata('logged_in', $sess_array);
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('check_database', 'Invalid username or password');
			return false;
		}
	}
}
